﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace Red.Controls.Extensions
{
    /// <summary>
    ///     Extensions for TextBox control
    /// </summary>
    public static class TextBoxExtensions
    {
        #region SelectAllOnFocus

        public static readonly DependencyProperty SelectAllOnFocusProperty =
            DependencyProperty.RegisterAttached( "SelectAllOnFocus", typeof( bool ), typeof( TextBoxExtensions ),
                new PropertyMetadata( false, HandleSelectAllOnFocusChanged ) );

        public static bool GetSelectAllOnFocus( DependencyObject element )
        {
            return (bool)element.GetValue( SelectAllOnFocusProperty );
        }

        public static void SetSelectAllOnFocus( DependencyObject element, bool value )
        {
            element.SetValue( SelectAllOnFocusProperty, value );
        }

        private static void HandleSelectAllOnFocusChanged( DependencyObject obj, DependencyPropertyChangedEventArgs e )
        {
            TextBox element = obj as TextBox;
            if ( element == null )
                throw new ArgumentException( "Invalid object type" );

            element.GotKeyboardFocus -= TextBox_GotKeyboardFocus;
            if ( true.Equals( e.NewValue ) )
                element.GotKeyboardFocus += TextBox_GotKeyboardFocus;
        }

        private static void TextBox_GotKeyboardFocus( object sender, KeyboardFocusChangedEventArgs e )
        {
            var txt = e.NewFocus as TextBox;
            if ( txt != null )
            { // only react to tab-focus, not mouse (it's already handled by double-click)
                if ( e.KeyboardDevice.IsKeyDown( Key.Tab ) || e.KeyboardDevice.IsKeyDown( Key.Enter ) ) 
                {
                    txt.SelectAll();
                }
            }
        }
        
        #endregion SelectAllOnFocus
    }
}
